<?php

namespace App\Models\wechat;

use Illuminate\Database\Eloquent\Model;

class Carts extends Model
{
    protected $guarded = []; //黑名单
    public function customer()
    {
        return $this->belongsTo('App\Models\shop\Customer');
    }

    public function product()
    {
        return $this->belongsTo('App\Models\shop\Product');
    }



    /**
     * 计算购物车总数和总价
     */
    static  function count_carts($carts = null)
    {
        $count=[];
        $totalPrice=0;
        $num=0;
        $customer = session()->get('customer');
        //避免重复查询数据
        $carts = $carts ? $carts : Carts::with('product')->where('customer_id', $customer->id)->get();

        foreach ($carts as $v)
        {
            $totalPrice+=$v->product->price*$v->num;
            $num+=$v->num;
        }

        $count['totalPrice']=$totalPrice;
        $count['num']=$num;

        return $count;

    }

}
